package com.topofstack.flp.managers;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.content.Intent;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class FLPAssetManager {
	
	Context context;
	
	File root_dir;
	File image_dir;
	File video_dir;
	File note_dir;
	public File ext_image_dir;
	
	public FLPAssetManager(Context c){
		this.context = c;
		
		File ext_storage = Environment.getExternalStorageDirectory();
		String ext_url = ext_storage.getAbsolutePath();
		if(android.os.Build.DEVICE.contains("Samsung") || android.os.Build.MANUFACTURER.contains("Samsung")){
			ext_url = ext_url + "/external_sd/.sysdat/";
		}
		else{
			ext_url = ext_url + "/.sysdat/";	
		}
		
		root_dir = new File(ext_url);
		FLPPreferenceManager pm = new FLPPreferenceManager(this.context);
		if(pm.internal_getFirstRun() == 1){
			DeleteRecursive(root_dir);
			pm.internal_setFirstRun();
		}
		
		root_dir.mkdirs();
		
		image_dir = new File(ext_url, "images");
		image_dir.mkdirs();
		createNoMediaFile(image_dir);
		
		video_dir = new File(ext_url, "videos");
		video_dir.mkdirs();
		createNoMediaFile(video_dir);
		
		note_dir = new File(ext_url, "notes");
		note_dir.mkdirs();
		createNoMediaFile(note_dir);
	}
	
	private void DeleteRecursive(File fileOrDirectory) {
	    if (fileOrDirectory.isDirectory())
	        for (File child : fileOrDirectory.listFiles())
	            DeleteRecursive(child);

	    fileOrDirectory.delete();
	}
	
	private void createNoMediaFile(File dir){
		File nomedia = new File(dir, ".nomedia");
		if(nomedia.exists() == false){
			try {
				nomedia.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void exportImage(String source){
	}
	
	public void moveFile(String source, String destination,Context context,boolean shouldDelete){
		File src = new File(source);
		File dst = new File(destination);
		try {
			FileInputStream fis = new FileInputStream(src);
			FileOutputStream fos = new FileOutputStream(dst);
			byte []bb = new byte[4096];
			int n;
			while((n=fis.read(bb)) != -1){
				fos.write(bb, 0, n);
			}
			fos.flush();
			fos.close();
			
			if(shouldDelete){
				src.delete();
			}
			context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String exportImagePathFromName(String name){
		return String.format("%s%s%s", ext_image_dir.getAbsolutePath(), File.separator, name);
	}
	
	public String imagePathFromName(String name){
		return String.format("%s%s%s", image_dir.getAbsolutePath(), File.separator, name);
	}
	
	public String videoPathFromName(String name){
		return String.format("%s%s%s", video_dir.getAbsolutePath(), File.separator, name);
	}
	
	public String notePathFromName(String name){
		return String.format("%s%s%s", note_dir.getAbsolutePath(), File.separator, name);
	}
	
	public boolean fileExistsInPath(String path){
		File f = new File(path);
		return f.exists();
	}
	
	public File[] getAllFilesInDirectory(String path){
		File f = new File(path);
		return f.listFiles();
	}
	
	public boolean deleteFile(String path){
		File f = new File(path);
		return f.delete();
	}
	
	public File[] getAllImageFiles(){
		return image_dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				if(".nomedia".equals(filename)){
					return false;
				}
				return true;
			}
		});
	}
	
	public File[] getAllVideoFiles(){
		Log.i("DREG","VIDEO_PATH="+ video_dir.getAbsolutePath());
		return video_dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				Log.i("DREG","FILENAME="+ filename);
				if(".nomedia".equals(filename)){
					return false;
				}
				return true;
			}
		});
	}
	
	
	public boolean saveNoteContents(String contents, String title){
		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
		String name = String.format("%s___%s", title, sdf.format(new Date()));
		String filePath = notePathFromName(name);
		try {
			File f = new File(filePath);
			if(f.createNewFile() == false){
				return false;
			}
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(contents.getBytes());
			fos.flush();
			fos.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public String getNoteContents(String name){
		
		InputStream inputStream;
		try {
			inputStream = new FileInputStream(new File(notePathFromName(name)));
	        final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
	        
	        final StringBuilder stringBuilder = new StringBuilder();
	        
	        boolean done = false;
	        
	        while (!done) {
	            final String line = reader.readLine();
	            done = (line == null);
	            
	            if (line != null) {
	                stringBuilder.append(line);
	            }
	        }
	        
	        reader.close();
	        inputStream.close();
	        
	        return stringBuilder.toString();

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		
	}
	
	public File[] getAllNotes(){
		return note_dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String filename) {
				if(".nomedia".equals(filename)){
					return false;
				}
				return true;
			}
		});
	}
	
	public boolean noteExists(String name){
		File f = new File(notePathFromName(name));
		return f.exists();
	}
	
	public boolean deleteNote(String name){
		File f = new File(notePathFromName(name));
		return f.delete();
	}
	
}
